import jwt
from datetime import datetime, timedelta
from django.conf import settings
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import Employee

class JWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        if not auth_header:
            return None
        
        try:
            # 检查是否是 Bearer token
            parts = auth_header.split()
            if len(parts) != 2 or parts[0].lower() != 'bearer':
                return None
            
            token = parts[1]
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            user = Employee.objects.get(id=payload['user_id'])
            if not user.is_active:
                raise AuthenticationFailed('用户已被禁用')
            return (user, None)
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('token已过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('token无效')
        except Employee.DoesNotExist:
            raise AuthenticationFailed('用户不存在')

def generate_token(user):
    payload = {
        'user_id': user.id,
        'exp': datetime.utcnow() + timedelta(days=1)
    }
    return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') 